import socket
import threading
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from common.utils import decode_dat

class net_Driver(QObject):

    # 定义信号
    on_rev_signal = pyqtSignal(int, str)

    def __init__(self) -> None:
        super().__init__()
        self.tcp_client: socket.socket = None

    def send_msg(self,text):
        self.tcp_client.send(text.encode())

    def tcp_is_connected(self):
        return self.tcp_client is not None

    def tcp_disconnected(self):
        self.tcp_client.close()
        self.tcp_client =None

    def run_tcp_client(self, target_ip, target_port):
        # 创建socket对象
        self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 连接                               !端口需要整数
        try:
            self.tcp_client.connect((target_ip, int(target_port)))

        # 发送消息  （通过发送框点击按钮发送）
        # tcp_client.send("您好啊123".encode())
        except Exception as e:
            print("连接服务器失败，请重试")
            self.tcp_client = None
            return
        # local_ip,local_port = self.tcp_client.getsockname()
        # print(f"连接成功ip={local_ip},port={local_port}")
        print("连接成功")
        # 连接成功后修改图标为连接
        # self.update_connect_state()
        self.on_rev_signal.emit(0, "None")

        try:
            while True:
                bytes_dat = self.tcp_client.recv(1024)
                if bytes_dat:
                    msg = decode_dat(bytes_dat)
                    # print(msg)
                    # 子线程不能直接操作主线程的ui组件否则可能出现争取问题
                    # self.ui.edit_rev.appendPlainText(msg)
                    self.on_rev_signal.emit(1, msg)

                else:
                    print("服务器断开连接")
                    break
        except:
            print("客户端断开连接")
        if self.tcp_client is not None:
            self.tcp_client.close()
            self.tcp_client = None

        # 如果到这肯定断开连接
        self.on_rev_signal.emit(0, "None")

    def connect_server(self, target_ip, target_port):
        t1 = threading.Thread(
            target=self.run_tcp_client, args=(target_ip, target_port), daemon=True
        )
        t1.start()
